package se.chalmers.tda366.crumble.gui.utils;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import se.chalmers.tda366.crumble.core.IArticle;
import se.chalmers.tda366.crumble.resources.Constants;


public final class CrumbleMouseListener implements MouseListener{
	
	private IArticle article;
	
	public CrumbleMouseListener(){
		initCtrl();
	}

	private void initCtrl() {
		//browse = ActionFactory.getControl(Ctrl.SHOW_ARTICLE_IN_BROWSER);
	}

	public void mouseClicked(MouseEvent e) {
		article = ((IArticleLink)e.getSource()).getArticle();
		if(e.getButton() == MouseEvent.BUTTON3){
			JMenuItem showArticle = new JMenuItem("Open article in browser");
			showArticle.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent evt) {
					try {
						java.awt.Desktop.getDesktop().browse(new URI(article.getSource()));
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (URISyntaxException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
			JPopupMenu jpop;
			jpop = new JPopupMenu();
			jpop.add(showArticle);
			jpop.show(e.getComponent(), e.getX(), e.getY());
		}else{
			GuiObserv.getInstance().fireNotify(((IArticleLink)e.getSource()), Constants.Actions.SHOW_ARTICLE);
		}
	}


	public void mouseEntered(MouseEvent e) {
		e.getComponent().setForeground(Color.DARK_GRAY);
		e.getComponent().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));	
	}

	public void mouseExited(MouseEvent e) {
		e.getComponent().setForeground(Color.BLACK);
		
	}


	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
	
}
